# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:
import requests
from lxml import etree
from setting import *

class citroenLogin:

    def __init__(self):
        self.indexUrl = 'http://service.citroen.com/pages/index.jsp'
        self.indexUrl_CN = 'http://service.citroen.com/do/changerParametres'
        self.loginUrl = 'http://service.citroen.com/do/login'
        self.vinUrl = 'http://service.citroen.com/do/ok'
        self.carsInfoUrl = 'http://service.citroen.com/docapvAP/caracteristique.do'
        self.cookies = {}
        self.headers = {
            "Host": "service.citroen.com",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
            # "": "",
        }

    def updateCookies(self, cookies):
        for k in cookies:
            self.cookies[k] = cookies[k]

    def updateHeaders(self, headers):
        for k in headers:
            self.headers[k] = headers[k]

    def _get_cookies_str(self, cookies):
        cookieStr = ""
        for k, v in cookies.items():
            value = '%s=%s; ' % (k, v)
            cookieStr += value
        return cookieStr.strip('; ')

    def handleCookies(self, currenCookies):
        c_l = []
        for k in currenCookies:
            v = currenCookies.get(k)
            s = "{}={}".format(k, v)
            c_l.append(s)
        return "; ".join(c_l)

    def login(self):
        # 请求登录页
        try:
            response = requests.get(url=self.indexUrl, headers = self.headers, timeout=30, allow_redirects=False)
            index_html = etree.HTML(response.content.decode('utf8'))
            window_value = index_html.xpath('//input[@name="window"]/@value')[0]
            cookies = response.cookies.get_dict()
            self.updateCookies(cookies)
            # 改为中文
            # 先增加cookies
            self.updateCookies({"Enabled": "true", "CodeLanguePaysOI": "zh_CN"})
            self.updateHeaders({"Referer": self.indexUrl})
            response = requests.get(url=self.indexUrl_CN, headers=self.headers, timeout=30, allow_redirects=False)
            self.updateCookies(response.cookies.get_dict())

            # 登录
            post_data = {
                "userid": cp_username,
                "password": cp_password,
                "window": window_value,
            }
            response = requests.post(url=self.loginUrl, data=post_data, headers=self.headers, cookies=self.cookies, timeout=60)

            self.updateCookies(response.cookies.get_dict())
            self.updateHeaders({"Referer": response.url})

            cookies_str = self.handleCookies(self.cookies)
            print(cookies_str)
            setData = {
                "cookies": cookies_str,
                "params": self.headers.get("Referer", "")
            }
            # logging.info("Login Success")
            return True, setData
        except:
            # logging.info("Login Fail")
            return False, {}


    def run(self):
        try:
            self.login()
        except Exception as e:
            print(e.__repr__())


if __name__ == '__main__':
    tools = citroenLogin()
    tools.run()